﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Windows.Forms;
using System.IO;

using ZJreport.Collection;
using ZJreport.Utils;

namespace ZJreport
{
    public partial class zjForm : Form
    {
        Merge1002 merge;
        PrintDialog printDialog;
        PrintDocument printDocument;
        PrintPreviewDialog printPreviewDialog;
        PageSetupDialog pageSetupDialog;

        public zjForm()
        {
            InitializeComponent();
                        
            printDocument = new PrintDocument();
            printDocument.PrintPage += new PrintPageEventHandler(this.printDocument_PrintPage);

            printPreviewDialog = new PrintPreviewDialog();
            printPreviewDialog.Document = printDocument;

            pageSetupDialog = new PageSetupDialog();
            pageSetupDialog.Document = printDocument;

            printDialog = new PrintDialog();
            printDialog.Document = printDocument;
      
        }

        private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            StringReader lineReader = new StringReader(richTextBox1.Text);
            Graphics g = e.Graphics; //获得绘图对象
            float linesPerPage = 0; //页面的行号
            float yPosition = 0;   //绘制字符串的纵向位置
            int count = 0; //行计数器
            float leftMargin = e.MarginBounds.Left; //左边距
            float topMargin = e.MarginBounds.Top; //上边距
            string line = null;
            Font printFont = this.richTextBox1.Font; //当前的打印字体
            SolidBrush myBrush = new SolidBrush(Color.Black);//刷子
            linesPerPage = e.MarginBounds.Height / printFont.GetHeight(g);//每页可打印的行数
            //逐行的循环打印一页
            while (count < linesPerPage && ((line = lineReader.ReadLine()) != null))
            {
                yPosition = topMargin + (count * printFont.GetHeight(g));
                g.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());
                count++;
            }

            if (line != null)
                e.HasMorePages = true;
            else
                e.HasMorePages = false;
        }

        void showRpt1002(Rpt1002 rpt1002)
        {

            showTransItems(rpt1002.GetTransItemCollection(), true);

        }

        void showTransItems(TransItemCollection collection, bool clear)
        {
            if (clear)
            {
                richTextBox1.Clear();
            }
            string transHead = "交易类型       ";
            string numHead = "    交易笔数";
            string capitalDebtHead = "   （交易金额)借";
            string capitalCreditHead = "   （交易金额)贷";
            string feeDebtHead = "   (费用)借";
            string feeCreditHead = "   (费用)贷";
            string sumDebtHead = "   (资金清算差额)借";
            string sumCreditHead = "   (资金清算差额)贷";
            StringBuilder builder = new StringBuilder();
            builder.Append(Helper.LeftPad(transHead, 36, ' '));
            builder.Append(Helper.LeftPad(numHead, 10, ' '));
            builder.Append(Helper.LeftPad(capitalDebtHead, 18, ' '));
            builder.Append(Helper.LeftPad(capitalCreditHead, 18, ' '));
            builder.Append(Helper.LeftPad(feeDebtHead, 14, ' '));
            builder.Append(Helper.LeftPad(feeCreditHead, 14, ' '));
            builder.Append(Helper.LeftPad(sumDebtHead, 18, ' '));
            builder.Append(Helper.LeftPad(sumCreditHead, 18, ' '));
            builder.Append("\r\n");

            richTextBox1.Text += builder.ToString();

            IList<TransItem> list = collection.GetTransItemList();
            TransItem[] itemArr = new TransItem[list.Count];
            list.CopyTo(itemArr, 0);

            Array.Sort(itemArr);

            for (int i = 0; i < itemArr.Length; i++)
            {
                richTextBox1.Text += itemArr[i].ToString();
            }

        }

        void showTransItems(Merge1002 merge)
        {
            richTextBox1.Clear();
            IList<string> instList = merge.GetMergedInstList();
            IList<string> settleDateList = merge.GetMergedSettleDateList();

            richTextBox1.Text += "以下是包括了下述机构的1002报表的交易汇总：";
            for (int i = 0; i < instList.Count; i++)
            {
                string str = "{" + instList[i] + ":" + settleDateList[i] + "} ";
                richTextBox1.Text += str;
            }

            richTextBox1.Text += "\r\n\r\n";

            showTransItems(merge.GetItemCollection(), false);
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            FileInfo info = new FileInfo(openFileDialog1.FileName);
            if (!info.Name.StartsWith("RD1002"))
            {
                MessageBox.Show("请选择RD1002文件!");
                return;
            }

            if (Helper.ExisInListBox(info.FullName, listBox1) ){
                MessageBox.Show(info.FullName + "  已经导进程序中，不能重复导入！");
                return;
            }
            
            Rpt1002 rpt1002 = new Rpt1002(info.FullName);
            
            //listBox1.Items.Add(rpt1002.InstCode + " " + rpt1002.SettleDate + " " + info.Name);
            listBox1.Items.Add(rpt1002);
        }

        //private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        //{
        //    label1.Text = "";
        //    Rpt1002 rpt = (Rpt1002)listBox1.SelectedItem;
        //    showRpt1002(rpt);
        //    label1.Text = "下面显示的是" + rpt.ToString();
        //}

        private void btnCombine_Click(object sender, EventArgs e)
        {
            label1.Text = "";
            //TransItemCollection result = new TransItemCollection();
            merge = new Merge1002();
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                Rpt1002 rpt = (Rpt1002)listBox1.Items[i];
                //result.Merge(rpt.GetTransItemCollection());
                merge.Merge(rpt);
            }

            showTransItems(merge);
            label1.Text = "下面显示的是左边所有文件之和";
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (merge == null)
            {
                MessageBox.Show("请先点击左边的“合并上述文件”按钮，然后才能导出");
                return;
            }
            saveFileDialog1.Filter = "Excel文档(*.xls)|*.xls";
            saveFileDialog1.Title = "导出为Excel(2003)文档";
            saveFileDialog1.ShowDialog();
            
           
        }

        private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            if (Helper.SaveToExcel(merge, saveFileDialog1.FileName))
                MessageBox.Show("成功保存在" + saveFileDialog1.FileName);
            else
                MessageBox.Show("保存不成功，请检查原因：如果是覆盖现有的文件，请将该Excel文件关闭，再尝试保存");
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            pageSetupDialog.PageSettings.Landscape = true;
            pageSetupDialog.ShowDialog();
            printPreviewDialog.ShowDialog();

            //try
            //{
            //    printDialog.ShowDialog();    
            //}
            //catch (Exception excep)
            //{
            //    MessageBox.Show(excep.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
        }


    }
}